$(function () {
    var params = Params();

    $('#search').val(params.search);
    params.search = params.search ? params.search : '';
    addProductHtml('gitList', 20, params.search);

    $('#sort').on('click', 'li.clickLi', function () {
        addProductHtml($(this).attr('data-query'), 20, params.search);
    });
    addShopCart();

    function addShopCart() {
        $('#proList').on('click', '.add-shop-cart', function () {
            var list = $(this).parents('li');
            var proId = list.attr('data-id');
            var color = list.attr('data-color');
            var postData = {
                postType: 'addCart',
                id: proId,
                color: color,
                num: 1
            };
            qingQiuPhp('post', 'admin/productList.php', postData, function (res) {
                alert(res.msg);
            });
        })
    }

    function addProductHtml(Type, number, search) {
        qingQiuPhp('get', 'admin/productList.php', {getType: Type, num: number, search: search}, function (res) {
            if (res.length < 1) {
                $('#proList').html('<p class="prompt">没有结果</p>');
            } else {
                addChaZhaoHtml(res);
            }
        });
    }

    function addChaZhaoHtml(res) {
        var str = '';
        for (var i = 0, n = res.length; i < n; i++) {
            var color = (res[i].color).split(/[,\;\uff0c\.]/)[0];
            str +=
                '<li data-id="' + res[i].id + '" data-color="' + color + '">'
                + '<a href="pro_details.html?id=' + res[i].id + '">'
                + '<img src="' + res[i].imgSrc + '" alt="">'
                + '</a>'
                + '<p>' + res[i].title + '</p>'
                + '<i>￥<span>' + res[i].price + '</span></i>'
                + '<strong class="add-shop-cart addShopCart">加入购物车</strong>'
                + '</li>';
        }
        $('#proList').html(str);
    }

    function Params() {
        var result = {}, hash = location.hash, search = location.search;
        result.docName = decodeURIComponent(location.pathname).match(/\/([^\/]+)\.html$/)[1];//提取文件名
        if (hash) {
            result.hash = hash.replace(/^\#/, ''); //提前锚点
        }
        if (search) {
            var arr = search.replace(/^\?/, '').split(/\&/g); //提前所有search参数
            for (var i = 0, n = arr.length; i < n; i++) {
                var key = arr[i].split(/\=/)[0];
                result[key] = decodeURIComponent(arr[i].split(/\=/)[1]);
            }
        }
        return result;
    }
});